package com.zgg.base;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.Date;
import java.util.Map;

public class BaseController {

    public final Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());

    /**
     * 返回json参数
     *
     * @param msgCode
     * @param data
     * @param msg
     * @return
     */
    public JSONObject returnResult(Integer msgCode, Object data, String msg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgCode", msgCode);
        jsonObject.put("data", data);
        jsonObject.put("msg", msg);
        return jsonObject;
    }

    public ResponseEntity export(JSONObject jsonObject) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_JSON_UTF8).body(jsonObject);

    }


    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + "." + file.getName().split("\\.")[1]);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));


        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

    /**
     * 返回页面数据
     *
     * @param path
     * @param result
     * @return
     */
    public ModelAndView returnView(String path, Map<String, Object> result) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(path);
        modelAndView.addAllObjects(result);
        return modelAndView;
    }
}
